package com.zzti.util;

import cn.hutool.core.util.IdUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.zzti.pojo.SysResult;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 对象存储的api
 * </p>
 *
 * @author zh
 * @since 2021/5/29
 */
@Component
public class CosApi {

    @Autowired
    private COSClient cosClient;

    private static final String BUCKET_NAME = "test-1306040600";

    /**
     * 返回存储对象的url
     *
     * @param localFile 要存储的对象
     * @return 返回存储对象的url
     */
    public SysResult uploadObject(MultipartFile localFile) {
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = getUploadName(localFile);
        PutObjectRequest putObjectRequest = null;
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 设置 Content type, 默认是 application/octet-stream
            objectMetadata.setContentType("image/jpeg");
            putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, localFile.getInputStream(), objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
        }
        cosClient.putObject(putObjectRequest);
        //https://test-1306040600.cos.ap-nanjing.myqcloud.com/black.jpg
        String url = getCosUrl(key);
        return SysResult.success(url);
    }

    private String getCosUrl(String key) {
        return "https://" + BUCKET_NAME + ".cos.ap-nanjing.myqcloud.com/" + key;
    }

    // 生成一个新的文件名 防止原文件名称与之前的存储名称相同
    private String getUploadName(MultipartFile localFile) {
        // 取原始文件名
        String oldName = localFile.getOriginalFilename();
        // 生成新文件名
        String dateStr = new DateTime().toString("-yyyy-MM-dd");
        String newName = IdUtil.simpleUUID().substring(10) + dateStr;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));
        return newName;
    }

}
